package com.dp.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.pojo.NewsBlacklistVo;
import com.dp.service.impl3.BaseImpl;
import com.dp.util.DataMap;
import com.dp.vo.NewsBlacklist;

@Service
@Transactional
public class BlacklistServiceImpl extends BaseImpl {
	
	/**
	 * Find all the NewsBlacklist Entity
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<NewsBlacklistVo>
	 */
	public List<NewsBlacklistVo> findAllBlacklistEntity(DataMap hashMap, Integer firstrow,
			Integer maxrow){
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		NewsBlacklistVo black=(NewsBlacklistVo) hashMap.get("black");
		StringBuffer sf = new StringBuffer("SELECT n.id,n.clientid,n.name,n.email,n.mobile,n.lastupdatetime,n.userid,n.issystem,n.isup,n.isdown,nc.mencoding ");
		if(black!=null&&(black.getSn()!=null&&black.getSn().toString().trim().length() > 0
		||black.getClientid()!=null&&black.getClientid().toString().trim().length() > 0
		||black.getName()!=null&&black.getName().toString().trim().length() > 0
		||black.getEmail()!=null&&black.getEmail().toString().trim().length() > 0
		||black.getMobile()!=null&&black.getMobile().toString().trim().length() > 0)){
					sf.append(" from news_blacklist n,news_clientinfo nc where n.clientid=nc.clientid ");
		}else{
			sf.append(" from news_blacklist n left join news_clientinfo nc on n.clientid=nc.clientid ");
		}
		if(black!=null){
			if(black!=null&&black.getSn()!=null&&black.getSn().toString().trim().length() > 0){
				sf.append(" AND nc.mencoding like '%"
						+ black.getSn().toString().trim() + "%'");
			}
			if(black.getClientid()!=null&& black.getClientid().toString().trim().length() > 0){
				sf.append(" AND n.clientid='"
						+ black.getClientid().toString().trim() + "'");
			}
			if(black.getName()!=null&& black.getName().toString().trim().length() > 0){
				sf.append(" AND n.name like '%"
						+ black.getName().toString().trim() + "%'");
			}
			if(black.getEmail()!=null&& black.getEmail().toString().trim().length() > 0){
				sf.append(" AND n.email like '%"
						+ black.getEmail().toString().trim() + "%'");
			}
			if(black.getMobile()!=null&& black.getMobile().toString().trim().length() > 0){
				sf.append(" AND n.mobile like '%"
						+ black.getMobile().toString().trim() + "%'");
			}
			
		}
		
		Object role_id = hashMap.get("role_id");
	    Object user_id = hashMap.get("user_id");
		if(StringIsNotNull(role_id) && StringIsNotNull(user_id))
	    {
			sf.append(" AND userid='" + user_id + "'");
	    }
		
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sf.append(" order by n."+jpage.getSidx());
				if("clientid".equals(jpage.getSidx())){
					sf.append("*1");
				}		
			    sf.append(" "+jpage.getSord());
			}
		}
		List<NewsBlacklistVo> result=null;
		try {
			Query query = em.createNativeQuery(sf.toString());
			if (firstrow != null) {
				query.setFirstResult(firstrow);
			}
			if (maxrow != null) {
				query.setMaxResults(maxrow);
			}
			List<Object[]>lll =  query.getResultList();
			if(lll.size()>0){
				NewsBlacklistVo blackVo=null;
				result=new ArrayList<NewsBlacklistVo>();
				SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for(int i=0;i<lll.size();i++){
					blackVo=new NewsBlacklistVo();
					blackVo.setId((Integer)lll.get(i)[0]);
					blackVo.setClientid((String)lll.get(i)[1]);
					blackVo.setName((String)lll.get(i)[2]);
					blackVo.setEmail((String)lll.get(i)[3]);
					blackVo.setMobile((String)lll.get(i)[4]);
					blackVo.setLastupdatetime(lll.get(i)[5]!=null?fmt_temp.parse(lll.get(i)[5].toString()):null);
					blackVo.setUserid((String)lll.get(i)[6]);
					blackVo.setIssystem(lll.get(i)[7]+"");
					blackVo.setIsup(lll.get(i)[8]+"");
					blackVo.setIsdown(lll.get(i)[9]+"");
					blackVo.setSn((String)lll.get(i)[10]);
					result.add(blackVo);
				}
				
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	
	/**
	 * 获得所有黑名单信息总记录数
	 * @param hashMap
	 * @return int
	 */
	public int findAllBlacklistEntityCount(DataMap hashMap){
		NewsBlacklistVo black=(NewsBlacklistVo) hashMap.get("black");
		int r = 0; 
		try {
			StringBuffer sqlS = new StringBuffer("select count(n.clientid) ");
			if(black!=null&&(black.getSn()!=null&&black.getSn().toString().trim().length() > 0
			||black.getClientid()!=null&&black.getClientid().toString().trim().length() > 0
			||black.getName()!=null&&black.getName().toString().trim().length() > 0
			||black.getEmail()!=null&&black.getEmail().toString().trim().length() > 0
			||black.getMobile()!=null&&black.getMobile().toString().trim().length() > 0)){
				sqlS.append(" from news_blacklist n,news_clientinfo nc where n.clientid=nc.clientid ");
			}else{
				sqlS.append(" from news_blacklist n left join news_clientinfo nc on n.clientid=nc.clientid ");
			}
			if(black!=null){
				if(black.getSn()!=null&& black.getSn().toString().trim().length() > 0){
					sqlS.append(" AND nc.mencoding like '%"
							+ black.getSn().toString().trim() + "%'");
				}
				if(black.getClientid()!=null&& black.getClientid().toString().trim().length() > 0){
					sqlS.append(" AND n.clientid='"
							+ black.getClientid().toString().trim() + "'");
				}
				if(black.getName()!=null&& black.getName().toString().trim().length() > 0){
					sqlS.append(" AND n.name like '%"
							+ black.getName().toString().trim() + "%'");
				}
				if(black.getEmail()!=null&& black.getEmail().toString().trim().length() > 0){
					sqlS.append(" AND n.email like '%"
							+ black.getEmail().toString().trim() + "%'");
				}
				if(black.getMobile()!=null&& black.getMobile().toString().trim().length() > 0){
					sqlS.append(" AND n.mobile like '%"
							+ black.getMobile().toString().trim() + "%'");
				}
				if(black.getIssystem()!=null&& black.getIssystem().toString().trim().length() > 0){
					sqlS.append(" AND n.issystem='"
							+ black.getIssystem().toString().trim() + "'");
				}
				if(black.getIsup()!=null&& black.getIsup().toString().trim().length() > 0){
					sqlS.append(" AND n.isup='"
							+ black.getIsup().toString().trim() + "'");
				}
				if(black.getIsdown()!=null&& black.getIsdown().toString().trim().length() > 0){
					sqlS.append(" AND n.isdown='"
							+ black.getIsdown().toString().trim() + "'");
				}
			}
			Object role_id = hashMap.get("role_id");
		    Object user_id = hashMap.get("user_id");
			if(StringIsNotNull(role_id) && StringIsNotNull(user_id))
		    {
				sqlS.append(" AND userid='" + user_id + "'");
		    }
			sql=sqlS.toString();
			r=getOneInt();
		} catch (Exception e) {
			logger.info("findAllBlacklistEntityCount fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return r;
	}
	
	
	public NewsBlacklist findNewsBlacklistById(String id) {
		NewsBlacklist o = null;
		try {
			o = this.em.find(NewsBlacklist.class, id);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (o == null) {
			String msg = "Uh oh, '" + NewsBlacklist.class + "' object with id '" + id
					+ "' not found...";
			logger.warn(msg);
			throw new EntityNotFoundException(msg);
		}
	
		return o;
	}

	/**
	 * Update NewsBlacklist Entity
	 * @param NewsBlacklist
	 * @return Boolean
	 */
	public Boolean updateNewsBlacklist(NewsBlacklist black) {
		Boolean resultb=true;
		String jpql="SELECT n FROM NewsBlacklist n WHERE n.clientid=:clientid AND n.name=:name AND n.email=:email AND n.mobile=:mobile AND n.id!=:id";
		Query query = em.createQuery(jpql);
		query.setParameter("clientid",black.getClientid());
		query.setParameter("name", black.getName());
		query.setParameter("email", black.getEmail());
		query.setParameter("mobile", black.getMobile());
		query.setParameter("id", black.getId());
		NewsBlacklist black_temp= (NewsBlacklist) getSingleResult(query);
		if(black_temp!=null){
			resultb=null;
		}else{
			jpql="UPDATE NewsBlacklist n SET n.clientid=:clientid,n.name=:name,n.email=:email,n.mobile=:mobile,n.lastupdatetime=:lastupdatetime," +
				"  n.issystem=:issystem,n.isup=:isup,n.isdown=:isdown WHERE n.id=:id";
			query = em.createQuery(jpql);
			query.setParameter("id", black.getId());
			query.setParameter("clientid", black.getClientid());
			query.setParameter("name", black.getName());
			query.setParameter("email", black.getEmail());
			query.setParameter("mobile", black.getMobile());
			query.setParameter("lastupdatetime", black.getLastupdatetime());
			query.setParameter("issystem", black.getIssystem());
			query.setParameter("isup", black.getIsup());
			query.setParameter("isdown", black.getIsdown());
			int iCode=query.executeUpdate();
			if(iCode<0){
				return false;
			}
		}
		return resultb;
	}

	/**
	 * Delete NewsBlacklist Entity
	 * @param urlB
	 * @return boolean b
	 */
	public boolean deleteNewsBlacklistById(String id) {
		boolean b = false;
		try {
			String jpql="DELETE NewsBlacklist n WHERE n.id=:id";
			Query query = em.createQuery(jpql);
			query.setParameter("id", id);
			int iCode=query.executeUpdate();
			if(iCode>0){
				b = true;
			}
		} catch (Exception e) {
			logger.warn("deleteNewsBlacklistById fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return b;
	}

	/***
	 * addNewsBlacklist
	 * @param NewsBlacklist
	 * @return Boolean
	 */
	public Boolean addNewsBlacklist(NewsBlacklist black) {
		Boolean resultb=true;
		try {
			String jpql="SELECT n FROM NewsBlacklist n WHERE n.clientid=:clientid AND n.name=:name AND n.email=:email AND n.mobile=:mobile";
			Query query = em.createQuery(jpql);
			query.setParameter("clientid",black.getClientid());
			query.setParameter("name", black.getName());
			query.setParameter("email", black.getEmail());
			query.setParameter("mobile", black.getMobile());
			NewsBlacklist black_temp= (NewsBlacklist) getSingleResult(query);
			if(black_temp!=null){
				resultb=null;
			}else{
				em.persist(black);
			}
		} catch (Exception e) {
			logger.info("addNewsBlacklist fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
		}
		return resultb;
	}
	
	
	public Object getSingleResult(Query query) {
		Object o =null;
		try {
			o = query.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		} catch (NonUniqueResultException ex) {
			o = query.getResultList();
			return ((List) o).get(0);
		}
		return o;
	}
	public static boolean StringIsNotNull(Object str) {
        boolean b = false;
        try {
            if (!str.equals("") && !str.equals("null")) {
                b = true;
            }
        } catch (Exception e) {
        }
        return b;
    }

	public String findClientidBySN(String sn) {
		String clientid="";
		try {
			String jpql="SELECT max(n.clientid) FROM NewsClientinfo n WHERE n.mencoding=:mencoding AND n.mencoding!='' ";
			Query query = em.createQuery(jpql);
			query.setParameter("mencoding",sn);
			Object o=query.getSingleResult();
			if(o!=null){
				clientid=o.toString();
			}
		} catch (Exception e) {
			logger.info("findClientidBySN fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return clientid;
	}
}